package com.uzai.console.service.tb.tbtokenapi.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.enums.RedisCacheKeyEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.dto.tb.tbtokenapi.*;
import com.uzai.console.entity.TbTokenApi;
import com.uzai.console.mapper.TbTokenApiMapper;
import com.uzai.console.service.tb.tbtokenapi.TbTokenApiService;
import com.uzai.console.vo.tb.tbtokenapi.TbTokenApiAuthUrlVo;
import com.uzai.console.vo.tb.tbtokenapi.TbTokenApiInfoVo;
import com.uzai.console.vo.tb.tbtokenapi.TbTokenApiPageVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/***
* 运营商基本配置
* @author liuqi
* @date 2021年08月13日 11:34
*/
@Service
public class TbTokenApiServiceImpl implements TbTokenApiService {

   Logger logger = LoggerFactory.getLogger(TbTokenApiServiceImpl.class);

   @Autowired
   private TbTokenApiMapper tbTokenApiMapper;

   @Autowired
   private RedisTemplate redisTemplate;
   @Autowired
   private UzaiConsoleSysConfig uzaiConsoleSysConfig;

    /**
    * 查询淘宝联盟列表
    * @author liuqi
    * @date 2021/8/13 11:38
    * @param tbTokenApiQuery
    * @return null
    */
   public Page<TbTokenApiPageVo> findTbTokenApiList(TbTokenApiQuery tbTokenApiQuery){
       Integer now = DateUtil.getNowTime();

       //新建返回到页面的LIST对象
       List<TbTokenApiPageVo> tbTokenApiPageVoList = new ArrayList<>();

       //执行分页查询对象
       Page<TbTokenApi> page = new Page<>();
       tbTokenApiQuery.convert(page);
       ArrayList<TbTokenApi> tbOrderList =  tbTokenApiMapper.findByList(page, tbTokenApiQuery);
       if(tbOrderList != null && tbOrderList.size() > 0){
           for (TbTokenApi tbTokenApi : tbOrderList){
               TbTokenApiPageVo tbTokenApiPageVo = new TbTokenApiPageVo();
               BeanUtils.copyProperties(tbTokenApi, tbTokenApiPageVo);
               if(StringUtils.isNotBlank(tbTokenApi.getPids())){
                   tbTokenApiPageVo.setPidList(JSONObject.parseArray(tbTokenApi.getPids(), String.class));
               }

               //到期时间
               Integer expiretime = Tools.getInteger(tbTokenApi.getExptime());
               if(expiretime.intValue() <= now.intValue()){
                   tbTokenApiPageVo.setExpireStatus(0);  //已到期
               }else if(expiretime.intValue() > now && expiretime.intValue() <= now + 7*24*3600){
                   tbTokenApiPageVo.setExpireStatus(2);  //即将到期
               }else{
                   tbTokenApiPageVo.setExpireStatus(1);  //未到期
               }

               tbTokenApiPageVoList.add(tbTokenApiPageVo);
           }
       }

       //返回到页面分页对象
       Page<TbTokenApiPageVo> pageVo = new Page<>();
       BeanUtils.copyProperties(page, pageVo);
       pageVo.setRecords(tbTokenApiPageVoList);
       //将分页信息复制到返回到页面的分页MO当中
       return pageVo;
   }


    /**
    * 设置炮灰
    * @author liuqi
    * @date 2021/8/13 11:38
    * @param tbTokenApiSetPhDto
    * @return null
    */
   public void setPh(TbTokenApiSetPhDto tbTokenApiSetPhDto){
       if(tbTokenApiSetPhDto.getId() == null || tbTokenApiSetPhDto.getIsPh() == null || tbTokenApiSetPhDto.getPhOrderCount() == null){
           throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
       }

       TbTokenApi tbTokenApi = tbTokenApiMapper.selectById(tbTokenApiSetPhDto.getId(), tbTokenApiSetPhDto.getMerId());

       if(tbTokenApi == null){
           throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该淘宝联盟账号不存在");
       }

       tbTokenApi.setPhOrderCount(tbTokenApiSetPhDto.getPhOrderCount());
       tbTokenApi.setIsPh(tbTokenApiSetPhDto.getIsPh());
       //启动炮灰，需要将辅助关闭
       if(tbTokenApiSetPhDto.getIsPh().intValue() == 1){
           tbTokenApi.setIsAux(0);
       }

       tbTokenApiMapper.update(tbTokenApi);

   }

    /**
    * 设置辅助账号
    * @author liuqi
    * @date 2021/8/13 11:38
    * @param tbTokenApiSetAuxDto
    * @return null
    */
   public void setAux(TbTokenApiSetAuxDto tbTokenApiSetAuxDto){
       if(tbTokenApiSetAuxDto.getId() == null || tbTokenApiSetAuxDto.getIsAux() == null){
           throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
       }
       TbTokenApi tbTokenApi = tbTokenApiMapper.selectById(tbTokenApiSetAuxDto.getId(), tbTokenApiSetAuxDto.getMerId());
       if(tbTokenApi == null){
           throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该淘宝联盟账号不存在");
       }
       tbTokenApi.setIsAux(tbTokenApiSetAuxDto.getIsAux());
       //启动辅助，需要将炮灰关闭
       if(tbTokenApiSetAuxDto.getIsAux().intValue() == 1){
           tbTokenApi.setIsPh(0);
       }
       tbTokenApiMapper.update(tbTokenApi);

   }

    /***
    * 添加授权
    * @author liuqi
    * @date 2021/8/13 11:38
    * @param merId
    * @return null
    */
   public TbTokenApiAuthUrlVo addTbTokenApi(Long merId){
       //刷新授权的链接，将运营商ID放入自定义参数state当中，授权刷新之后，淘宝调用回调函数返回授权信息
       //淘宝联盟
       String merId_type =  merId + "_0";
       String url =  uzaiConsoleSysConfig.getTbTokenApiAuthorize() + merId_type;
       TbTokenApiAuthUrlVo tbTokenApiAuthUrlVo = new  TbTokenApiAuthUrlVo();
       tbTokenApiAuthUrlVo.setUrl(url);
       return tbTokenApiAuthUrlVo;
   }

    /***
    * 查询联盟详情
    * @author liuqi
    * @date 2021/8/13 11:38
    * @param tbTokenApiIdDto
    * @return null
    */
   public TbTokenApiInfoVo findTbTokenApiInfo(TbTokenApiIdDto tbTokenApiIdDto){

       if(tbTokenApiIdDto.getId() == null){
           throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
       }
       TbTokenApi tbTokenApi = tbTokenApiMapper.selectById(tbTokenApiIdDto.getId(), tbTokenApiIdDto.getMerId());
       if(tbTokenApi == null){
           throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该淘宝联盟账号不存在");
       }

       //返回页面对象
       TbTokenApiInfoVo tbTokenApiInfoVo = new TbTokenApiInfoVo();
       //将查询到的对象复制给返回页面对象
       BeanUtils.copyProperties(tbTokenApi, tbTokenApiInfoVo);

       if(StringUtils.isNotBlank(tbTokenApi.getPids())){
           tbTokenApiInfoVo.setPidList(JSONObject.parseArray(tbTokenApi.getPids(), String.class));
       }

       return tbTokenApiInfoVo;
   }

    /***
    * 修改联盟PID
    * @author liuqi
    * @date 2021/8/13 11:38
    * @param tbTokenApiUpdatePidDto
    * @return null
    */
   public void updatePid(TbTokenApiUpdatePidDto tbTokenApiUpdatePidDto){

       if(tbTokenApiUpdatePidDto.getId() == null){
           throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
       }

       if(tbTokenApiUpdatePidDto.getSettleType() == null){
           throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "比价订单行为未选择方式");
       }

       if(StringUtils.isBlank(tbTokenApiUpdatePidDto.getDefPid())){
           throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请设置默认PID");
       }

       TbTokenApi tbTokenApi = tbTokenApiMapper.selectById(tbTokenApiUpdatePidDto.getId(), tbTokenApiUpdatePidDto.getMerId());
       if(tbTokenApi == null){
           throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该淘宝联盟账号不存在");
       }

       tbTokenApi.setSettleType(tbTokenApiUpdatePidDto.getSettleType());
       tbTokenApi.setDefPid(tbTokenApiUpdatePidDto.getDefPid());
       tbTokenApi.setPids(JSONObject.toJSONString(tbTokenApiUpdatePidDto.getPidList()));
       tbTokenApi.setPidWlist(tbTokenApiUpdatePidDto.getPidWlist());
       tbTokenApiMapper.update(tbTokenApi);

       //设置redis
       //先删除pid队列
       redisTemplate.delete(String.format(RedisCacheKeyEnum.TB_PIDS_QUEUE.getKey(), tbTokenApi.getMerId(), tbTokenApi.getUserId()));
       //把pidList添加redis队列当中
       List<String> pidList = tbTokenApiUpdatePidDto.getPidList();
       if(pidList != null && pidList.size() > 0){
           for (String pid : pidList){
               redisTemplate.opsForList().leftPushAll(String.format(RedisCacheKeyEnum.TB_PIDS_QUEUE.getKey(), tbTokenApi.getMerId(), tbTokenApi.getUserId()), pid);
           }
       }
   }

    /***
    * 设置是否同步订单
    * @author liuqi
    * @date 2021/8/13 11:38
    * @param tbTokenApiIsSyncOrderDto
    * @return null
    */
   public void setIsSyncOrder(TbTokenApiIsSyncOrderDto tbTokenApiIsSyncOrderDto){
       if(tbTokenApiIsSyncOrderDto.getId() == null){
           throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
       }

       TbTokenApi tbTokenApi = tbTokenApiMapper.selectById(tbTokenApiIsSyncOrderDto.getId(), tbTokenApiIsSyncOrderDto.getMerId());

       if(tbTokenApi == null){
           throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此联盟不存在");
       }

       tbTokenApi.setIsSyncOrder(tbTokenApiIsSyncOrderDto.getIsSyncOrder());

       tbTokenApiMapper.update(tbTokenApi);
   }

    /***
    * 删除
    * @author liuqi
    * @date 2021/8/13 11:38
    * @param tbTokenApiIdDto
    * @return null
    */
   public void deleteTbTokenApi(TbTokenApiIdDto tbTokenApiIdDto){
       if(tbTokenApiIdDto.getId() == null){
           throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
       }

       TbTokenApi tbTokenApi = tbTokenApiMapper.selectById(tbTokenApiIdDto.getId(), tbTokenApiIdDto.getMerId());
       if(tbTokenApi != null){

           if(tbTokenApi.getType().intValue() == 2){ //淘宝和饿了么共享联盟
               tbTokenApi.setType(1); //修改成饿了么独享联盟
               tbTokenApiMapper.updateSelective(tbTokenApi);
           }else{
               tbTokenApiMapper.deleteById(tbTokenApiIdDto.getId(), tbTokenApiIdDto.getMerId());
               //删除redis
               redisTemplate.delete(String.format(RedisCacheKeyEnum.TB_PIDS_QUEUE.getKey(), tbTokenApi.getMerId(), tbTokenApi.getUserId()));
           }
       }

   }

}
